<template>
    <div>
        <el-upload
            action=""
            list-type="picture-card"
            :http-request="httpRequest"
            :on-preview="handlePictureCardPreview"
            :on-exceed="handleLimit"
            :limit="1"
            :disabled="this.$route.params.type=='look'"
            :file-list="fileList"
            >
            <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
    </div>
</template>

<script>
import axios from 'axios';
import {imageToBase64} from "@/api/imageToBase64"
import {base64ToFile} from "@/api/base64ToFile"
export default {
    data() {
      return {
        dialogImageUrl: '',
        dialogVisible: false,
        fileList:[]
      };
    },
    mounted(){
      this.$bus.on('sendUrl',async (val)=>{
        await (this.dialogImageUrl=val)
        // this.handleImgToBase64(this.dialogImageUrl,(res)=>{
        //     this.fileList=[{res}]
        // })
        this.fileList=[{url:this.dialogImageUrl}]  
      })
    },
    methods: {
      handleImgToBase64(url,cb){
        var image = new Image();
        image.crossOrigin = '';
        image.src = url;
        image.onload = function () {
          let base64 = imageToBase64(image); //图片转base64
          let file = base64ToFile(base64, 'file'); //base64转File
          this.fileList=[{file}]
          cb && typeof cb == 'function' && cb(file);
          return file;
        }
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      handleLimit(){
        this.$notify({
            title: '温馨提示',
            message: '仅可上传一张图片',
            type: 'warning'
        })
      },
      httpRequest(item){
        axios({
            url:'http://localhost:8080/kfc/upload',
            method:'post',
            headers:{
              token:localStorage.getItem('jwt'),
              'Content-Type': 'multipart/form-data'
            },
            data:{
              file:item.file
            }
          }).then(res=>{
            if(res.status==200){
              this.dialogImageUrl=res.data
              this.$emit('sendImg',this.dialogImageUrl)
              this.$notify({
                  title: '成功',
                  message: '附件上传成功',
                  type: 'success'
              })
            }
            else{
              this.$notify.error({
                  title: '错误',
                  message: '附件上传失败'
              })
            }
          })
      },
    }
}
</script>

<style>

</style>